<template>
  <div class="app-container">

    <div class="filter-container">
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="请输入硬件序列号" v-model="listQuery.equipmentId"></el-input>
      <el-select v-model="listQuery.online"   placeholder="是否在线">
          <el-option v-for="item in onlineOptions" :label="item.label" :value="item.value" :key="item.value"></el-option>
      </el-select>
      <el-button class="filter-item" type="primary" style="float:right;"  icon="el-icon-edit"  @click="handleReset()">重置</el-button>
      <el-button class="filter-item" type="primary" style="float:right;margin-right:10px;"  icon="el-icon-edit"  @click="handleCreate">新增</el-button>
      <el-button class="filter-item" type="primary" style="float:right;margin-right:10px;" v-waves icon="el-icon-search" @click="handleFilter">查询</el-button>
    </div>
    <el-table :key='tableKey' :data="list" v-loading="listLoading" element-loading-text="正在加载中" border fit highlight-current-row
      style="width: 100%">
      <el-table-column align="center" label="行号" width="45">
        <template slot-scope="scope">
          <span>{{scope.$index+1}}</span>
        </template>
      </el-table-column>
      <el-table-column width="110px" align="center" label="硬件序列号">
        <template slot-scope="scope">
          <span>{{scope.row.equipmentId }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column width="150px" align="center" label="日期">
        <template slot-scope="scope">
          <span>{{scope.row.gmtCreate | formatDatetime}}</span>
        </template>
      </el-table-column> -->
      <el-table-column min-width="100px" label="业务终端号">
        <template slot-scope="scope">
          <span class="link-type" >{{scope.row.imeiNo}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="100px" label="交易终端号">
        <template slot-scope="scope">
          <span class="link-type" >{{scope.row.equipmentNo}}</span>
        </template>
      </el-table-column>
      <el-table-column width="110px" align="center" label="厂商">
        <template slot-scope="scope">
          <span>{{scope.row.equipmentPro}}</span>
        </template>
      </el-table-column>
      <el-table-column width="110px" align="center" label="型号">
        <template slot-scope="scope">
          <span>{{scope.row.equipmentType}}</span>
        </template>
      </el-table-column>
      <el-table-column width="110px" align="center" label="商户号">
        <template slot-scope="scope">
          <span>{{scope.row.customerName}}</span>
        </template>
      </el-table-column>
      <el-table-column width="110px" align="center" label="备注">
        <template slot-scope="scope">
          <span>{{scope.row.remark}}</span>
        </template>
      </el-table-column>
      <el-table-column width="110px" align="center" label="ICCID号">
        <template slot-scope="scope">
          <span>{{scope.row.iccid}}</span>
        </template>
      </el-table-column>
      <el-table-column width="110px" align="center" label="应用版本号">
        <template slot-scope="scope">
          <span>{{scope.row.appVersion}}</span>
        </template>
      </el-table-column>
      <el-table-column width="110px" align="center" label="是否在线">
        <template slot-scope="scope">
          <span>{{scope.row.online | showOnline}}</span>
        </template>
      </el-table-column>
      <el-table-column width="150px" align="center" label="更新时间">
        <template slot-scope="scope">
          <span>{{scope.row.gmtModified | formatDatetime}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="500" class-name="small-padding fixed-width">
        <template slot-scope="scope">
         <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">修改</el-button>
         <el-button type="success" size="mini" @click="handleDetail(scope.row)">详情</el-button>
         <el-button type="info" size="mini" @click="handleStatus(scope.row)">状态</el-button>
         <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
         <el-button type="warning" size="mini" @click="posOperation(scope.row,0)">关机</el-button>
         <el-button type="warning" size="mini" @click="posOperation(scope.row,1)">重启</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="90px" style='width: 450px; margin-left:50px;'>
        <el-input type="hidden" v-model="temp.id"></el-input>
        <el-form-item label="硬件序列号" prop="equipmentId">
          <el-input v-model="temp.equipmentId"></el-input>
        </el-form-item>
        <el-form-item label="交易终端号" prop="equipmentNo">
          <el-input v-model="temp.imeiNo"></el-input>
        </el-form-item>
        <el-form-item label="厂商" prop="equipmentPro">
          <el-input v-model="temp.equipmentPro"></el-input>
        </el-form-item>
        <el-form-item label="终端型号" prop="equipmentType">
          <el-input v-model="temp.equipmentType"></el-input>
        </el-form-item>
        <el-form-item label="商户号" prop="customerName">
          <!-- <el-input v-model="temp.customerName"></el-input> -->
          <el-select v-model="temp.customerId" @change="selectGet" placeholder="请选择商户名称">
            <el-option v-for="item in customerData" :label="item.customerName" :value="item.id" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="业务终端号" prop="equipmentNo">
          <el-input v-model="temp.equipmentNo"></el-input>
        </el-form-item>
        <el-form-item label="ICCID号" prop="iccid">
          <el-input v-model="temp.iccid"></el-input>
        </el-form-item>
        <el-form-item label="版本号" prop="appVersion">
          <el-input v-model="temp.appVersion"></el-input>
        </el-form-item>
        <el-form-item label="存放地址" prop="equipmentAddress">
          <el-input v-model="temp.equipmentAddress"></el-input>
        </el-form-item>
        <el-form-item label="是否在线" prop="online">
          <el-select v-model="temp.online" @change="selectOnline"  placeholder="是否在线">
              <el-option v-for="item in onlineOptions" :label="item.label" :value="item.value" :key="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="remark" prop="remark">
          <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="Please input" v-model="temp.remark">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">cancel</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">confirm</el-button>
        <el-button v-else type="primary" @click="updateData">confirm</el-button>
      </div>
    </el-dialog>


    <el-dialog title="detail" :visible.sync="dialogDetailVisible">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="90px" style='width: 450px; margin-left:50px;'>
       <el-input type="hidden" v-model="temp.id"></el-input>
        <el-form-item label="硬件序列号" prop="equipmentId">
          <el-input v-model="temp.equipmentId"></el-input>
        </el-form-item>
        <el-form-item label="交易终端号" prop="imeiNo">
          <el-input v-model="temp.imeiNo"></el-input>
        </el-form-item>
        <el-form-item label="厂商" prop="equipmentPro">
          <el-input v-model="temp.equipmentPro"></el-input>
        </el-form-item>
        <el-form-item label="终端型号" prop="equipmentType">
          <el-input v-model="temp.equipmentType"></el-input>
        </el-form-item>
        <el-form-item label="商户号" prop="customerName">
          <el-input v-model="temp.customerName"></el-input>
        </el-form-item>
        <el-form-item label="业务终端号" prop="equipmentNo">
          <el-input v-model="temp.equipmentNo"></el-input>
        </el-form-item>
        <el-form-item label="ICCID号" prop="iccid">
          <el-input v-model="temp.iccid"></el-input>
        </el-form-item>
        <el-form-item label="版本号" prop="appVersion">
          <el-input v-model="temp.appVersion"></el-input>
        </el-form-item>
        <el-form-item label="存放地址" prop="equipmentAddress">
          <el-input v-model="temp.equipmentAddress"></el-input>
        </el-form-item>
        <el-form-item label="是否在线" prop="online">
          <el-select v-model="temp.online" @change="selectOnline"  placeholder="是否在线">
              <el-option v-for="item in onlineOptions" :label="item.label" :value="item.value" :key="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="remark" prop="remark">
          <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="Please input" v-model="temp.remark">
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogDetailVisible = false">CLOSE</el-button>
      </span>
    </el-dialog>

    <el-dialog title="终端在线" :visible.sync="dialogStatusVisible" width="80%" size="small">
        <el-row>
          <el-col :span="16">
            <div class="grid-content bg-purple amap-wrapper">
                <el-amap   id="mapcointainer"
            :zoom="zoom"
            :center="center">
              <el-amap-marker vid="component-marker" :position="componentMarker.position"  visible="true"></el-amap-marker>
            </el-amap>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="grid-content bg-purple-light" >
                <el-form :rules="rules" ref="dataForm" :model="deviceTemp" label-position="left" label-width="90px">
                     <el-form-item label="设备序列号" >
                      <el-input v-model="deviceTemp.device_id"></el-input>
                    </el-form-item>
                    <el-form-item label="状态" >
                      <el-input v-model="deviceTemp.status"></el-input>
                    </el-form-item>
                    <el-form-item label="最后响应时间" >
                      <el-input v-model="deviceTemp.lasttime"></el-input>
                    </el-form-item>
                    <el-form-item label="经度" >
                      <el-input v-model="deviceTemp.longitude"></el-input>
                    </el-form-item>
                    <el-form-item label="纬度" >
                      <el-input v-model="deviceTemp.Latitude"></el-input>
                    </el-form-item>
                    <el-form-item label="地理坐标名称" >
                      <el-input v-model="deviceTemp.address"></el-input>
                    </el-form-item>
                    <el-form-item label="打印机状态" >
                      <el-input v-model="deviceTemp.printer_status"></el-input>
                    </el-form-item>
                </el-form>
            </div>
          </el-col>
        </el-row>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="dialogStatusVisible = false">关闭</el-button>
        </span>
    </el-dialog>

  </div>
</template>

<script>
import { getTerminalList, saveTerminal, updateTerminal, getTerminalDetail, deleteTerminal } from '@/api/itims/itimsterminal'
import { getAllBusinessList } from '@/api/itims/itimsbusiness'
import { health, upgrade, result, posOperations } from '@/api/itims/terminalstatus'
import waves from '@/directive/waves' // 水波纹指令
import { parseTime, formatDate, formatDatetime  } from '@/utils'
import {lazyAMapApiLoaderInstance} from 'vue-amap'

export default {
  name: 'itimsTerminal',
  directives: {
    waves
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        equipmentId: undefined,
        page: 1,
        limit: 20,
        importance: undefined,
        title: undefined,
        type: undefined,
        sort: '+id',
        online: undefined
      },
      temp: {
        id:undefined,
        equipmentId: undefined,
        imeiNo: undefined,
        equipmentPro: undefined,
        equipmentType: undefined,
        customerId: undefined,
        customerName: undefined,
        equipmentAddress: undefined,
        equipmentNo: undefined,
        isDeleted:undefined,
        remark: undefined,
        online: undefined,
        onlinevalue: undefined,
        iccid: undefined,
        appVersion: undefined
      },
      deviceTemp:{
        lasttime: formatDate(new Date(),"yyyy-MM-dd hh:mm:ss"),
        device_id: '123456',
        status: '终端在线',
        longitude: '117.124966',
        Latitude: '36.653123',
        address: '山东高速大厦',
        printer_status: '',
      },
      customerData: [],
      onlineOptions: [{
          value: 0,
          label: '下线'
        }, {
          value: 1,
          label: '在线'
        }],
      dialogFormVisible: false,
      dialogStatusVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      dialogDetailVisible:false,
      pvData: [],
      rules: {
        equipmentId: [{ required: true, message: 'equipmentId is required', trigger: 'change' }],
        equipmentPro: [{ required: true, message: 'equipmentPro is required', trigger: 'change' }],
        online: [{ required: true, message: 'online is required', trigger: 'change' }],
        customerName: [{ required: true, message: '商户号 is required', trigger: 'change' }]
      },
      zoom:15,
      center:[117.124966,36.653123],
      componentMarker: {
        position: [117.124966,36.653123]
      }
    }
  },
  mounted() {
    lazyAMapApiLoaderInstance.load().then(() => {
        // your code ...
        this.map = new AMap.Map('mapcointainer', {
            center: new AMap.LngLat(this.deviceTemp.longitude,this.deviceTemp.latitude)
        });
    });
  },
  filters: {
    formatDate(time) {
       var date = new Date(time);
      return formatDate(date, 'yyyy-MM-dd hh:mm');
    },
    formatDatetime(time){
      return formatDatetime(time);
    },
    showOnline(online){
      if(online === 1){
        return "在线";
      }else{
        return "下线";
      }
    }
  },
  created() {
    this.getList()
    this.getCustomerDataList()
  },
  methods: {
    getList() {
      this.listLoading = true
      const param = {
        'body': {
          "itimsTerminalDTO":{
            "equipmentId":this.listQuery.equipmentId,
            "online": this.listQuery.online
          },
          "pageInfo":{
            "page":this.listQuery.page,
            "pageSize":this.listQuery.limit
          }
        }
      }
      getTerminalList(param).then(response => {
        this.list = response.body.itimsTerminalDTOList
        this.total = response.body.pageInfo.rowCount
        this.listLoading = false
      })
    },
    getCustomerDataList() {
        const treeparam = {
          'body': {
            "itimsBusinessDTO":{
            },
          }
        }
      getAllBusinessList(treeparam).then(response => {
        this.customerData = response.body.itimsBusinessDTOList
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id:undefined,
        equipmentId: undefined,
        imeiNo: undefined,
        equipmentPro: undefined,
        equipmentType: undefined,
        customerId: undefined,
        customerName: undefined,
        equipmentAddress: undefined,
        equipmentNo: undefined,
        isDeleted:undefined,
        remark: undefined,
        online: undefined,
        appVersion: undefined
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.onlinevalue = "下线"
      this.online = "0"
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const data = {
            'body': {
              "itimsTerminalDTO":{
                // "id":"ed55aec33d6c478cb44293f73429b44d",
                "equipmentId": this.temp.equipmentId,
                "imeiNo": this.temp.imeiNo,
                "equipmentPro": this.temp.equipmentPro,
                "equipmentType": this.temp.equipmentType,
                "customerId": this.temp.customerId,
                "customerName": this.temp.customerName,
                "equipmentAddress": this.temp.equipmentAddress,
                "equipmentNo": this.temp.equipmentNo,
                "isDeleted":"0",
                "remark": this.temp.remark,
                "online": this.temp.online,
                "iccid": this.temp.iccid,
                "appVersion": this.temp.appVersion
              }
            }
          }
          // this.temp.appId = parseInt(Math.random() * 100) + 1024 // mock a id
          this.temp.flag = 0
          saveTerminal(data).then(response => {
            this.list.unshift(response.body.itimsTerminalDTO)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.gmtModified = new Date()
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          const data = {
            'body': {
              "itimsTerminalDTO":{
                "id": this.temp.id,
                "equipmentId": this.temp.equipmentId,
                "imeiNo": this.temp.imeiNo,
                "equipmentPro": this.temp.equipmentPro,
                "equipmentType": this.temp.equipmentType,
                "customerId": this.temp.customerId,
                "customerName": this.temp.customerName,
                "equipmentAddress": this.temp.equipmentAddress,
                "equipmentNo": this.temp.equipmentNo,
                "isDeleted":"0",
                "remark": this.temp.remark,
                "online": this.temp.online,
                "iccid": this.temp.iccid,
                "appVersion": this.temp.appVersion
              }
            }
          }
          updateTerminal(data).then(response => {
            const businessDTO = response.body.itimsTerminalDTO;
            for (const v of this.list) {
              if (v.id === this.temp.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, tempData)
                break
              }
            }
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该终端信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
            const data = {
              'body': {
                  "itimsTerminalDTO":{
                    "id": row.id
                  }
                }
              }
            deleteTerminal(data).then(response => {
              const itimsTerminalDTO = response.body.itimsTerminalDTO;
              for (const v of this.list) {
                if (v.id === this.temp.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, itimsTerminalDTO)
                  break
                }
              }
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000
              })
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });

    },
    handleDetail(row) {
        this.temp = Object.assign({}, row) // copy obj
        this.dialogDetailVisible = true
    },
    //下拉框选中事件
    selectGet(vId){//这个vId也就是value值
      let obj = {};
      obj = this.customerData.find((item)=>{//这里的userList就是上面遍历的数据源
          return item.id === vId;//筛选出匹配数据
      });
      this.temp.customerId = obj.id;
      this.temp.customerName = obj.customerName;
    },
    selectOnline(vId){//这个vId也就是value值
      let obj = {};
      obj = this.onlineOptions.find((item)=>{//这里的userList就是上面遍历的数据源
          return item.value === vId;//筛选出匹配数据
      });
      this.temp.online = obj.value;
      this.temp.onlinevalue = obj.label
    },
    handleStatus(row) {
        const data = {
          'body': {
              "deviceDTO":{
                "device_id": row.equipmentId
              }
            }
        }
        health(data).then(response => {
            const deviceDTO = response.body.deviceDTO;
            if(deviceDTO.health){
              this.dialogStatusVisible = true
              this.deviceTemp.longitude = deviceDTO.longitude
              this.deviceTemp.latitude = deviceDTO.latitude
              this.deviceTemp.address = deviceDTO.address
              this.deviceTemp.health = deviceDTO.health
              this.deviceTemp.device_id = deviceDTO.device_id
              this.deviceTemp.lasttime = deviceDTO.lasttime
              this.deviceTemp.printer_status = deviceDTO.printer_status
              //printer_status
              this.componentMarker.position=[deviceDTO.longitude,deviceDTO.latitude]
              this.center=[deviceDTO.longitude,deviceDTO.latitude]
            }else{
              this.$alert('终端下线', '提示', {
              confirmButtonText: '确定',
              callback: action => {
                // this.$message({
                //   type: 'info',
                //   message: `action: ${ action }`
                // });
              }
            });
            }

      })
    },
    posOperation(row, type){

       this.$prompt('请输入指令密码', '提示', {
      // this.$confirm('确定下发命令， 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(({value}) => {
            if("123456a?" !== value){
              this.$message({
                type: 'warning',
                message: '指令密码错误,请重新下发！'
              });
              return
            }

             const param = {
                'body': {
                    "data":{
                      "type": type,
                      "device_id": row.equipmentId
                    }
                }
              }
              posOperations(param).then(response => {
                  const deviceDTO = response.body.code;
                  if(response.body.code === "000000"){
                    this.$alert('下发指令成功!', '提示', {
                      confirmButtonText: '确定',
                      callback: action => {
                      }
                    });
                  }else{
                    this.$alert('下发指令失败!', '提示', {
                      confirmButtonText: '确定',
                      callback: action => {
                      }
                    });
                }
            })

        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消下发'
          });
        });
    },
    handleReset(){
      this.listQuery.online = undefined
      this.listQuery.equipmentId = undefined
    }
  }
}
</script>

<style>
.amap-wrapper {
  width: 90%;
  height: 500px;
}
</style>
